package com.zhiqingchun.dao.mail.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.zhiqingchun.common.Page;
import com.zhiqingchun.dao.BaseDao;
import com.zhiqingchun.dao.mail.IMailDao;
import com.zhiqingchun.pojo.MailDO;

public class MailDao extends BaseDao implements IMailDao {

	@Override
	public List<MailDO> list(MailDO mailDO, Page page) {
		StringBuilder sql = new StringBuilder();
		sql.append("select m.*, u0.usr as usr0, u1.usr as usr1")
			.append(" from mail m, usr u0, usr u1 where m.fromsb = u0.id and m.tosb = u1.id");
		List<Object> param = new ArrayList<Object>();
		if (mailDO.getDirection() == 0) {
			sql.append(" and m.fromsb = ?");
			param.add(mailDO.getFromsb());
		} else if (mailDO.getDirection() == 1) {
			sql.append(" and m.tosb = ?");
			param.add(mailDO.getTosb());
		}
		sql.append(" and m.status >= ? order by m.insert_time desc");
		param.add(mailDO.getStatus());
		List<Map<String, Object>> returnList = getJdbcBaseDao().findPageList(sql.toString(), param.toArray(), page);
		List<MailDO> list = new ArrayList<MailDO>();
		for (Map<String, Object> map : returnList) {
			MailDO m = new MailDO();
			try {
				BeanUtils.populate(m, map);
				m.setInsertTime((Date) map.get("insert_time"));
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			list.add(m);
//			ArticleDO a = new ArticleDO();
//			a.setId(Integer.parseInt(map.get("id").toString()));
//			a.setTitle(map.get("title").toString());
//			Integer _comment =  Integer.parseInt(map.get("comment").toString());
//			Integer _collection = Integer.parseInt(map.get("collection").toString());
//			a.setCollection(_comment);
//			a.setComment(_collection);
//			a.setTotal(_comment * 2 + _collection);
//			a.setAuthorName(map.get("usr").toString());
//			a.setInsertTime(new Date());
//			list.add(a);
		}
		return list;
	}

}
